package scatter.order.rest.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import scatter.common.rest.exception.BusinessException;
import scatter.order.pojo.po.OrderRefund;
import scatter.order.rest.mapper.OrderRefundMapper;
import scatter.order.rest.service.IOrderNoGeneratorService;
import scatter.order.rest.service.IOrderRefundNoGeneratorService;
import scatter.order.rest.service.IOrderRefundService;
import scatter.common.rest.service.IBaseAddUpdateQueryFormServiceImpl;
import org.springframework.stereotype.Service;
import scatter.order.pojo.form.OrderRefundAddForm;
import scatter.order.pojo.form.OrderRefundUpdateForm;
import scatter.order.pojo.form.OrderRefundPageQueryForm;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 订单退款单表 服务实现类
 * </p>
 *
 * @author yw
 * @since 2021-08-07
 */
@Service
@Transactional
public class OrderRefundServiceImpl extends IBaseAddUpdateQueryFormServiceImpl<OrderRefundMapper, OrderRefund, OrderRefundAddForm, OrderRefundUpdateForm, OrderRefundPageQueryForm> implements IOrderRefundService {

    @Autowired
    private List<IOrderRefundNoGeneratorService> orderRefundNoGeneratorServices;


    @Override
    public void preAdd(OrderRefundAddForm addForm,OrderRefund po) {
        super.preAdd(addForm,po);
        if (!isStrEmpty(addForm.getRefundNo())) {
            // 退款单号已存在不能添加
            assertByColumn(addForm.getRefundNo(),OrderRefund::getRefundNo,false);
        }

    }

    @Override
    public void preUpdate(OrderRefundUpdateForm updateForm,OrderRefund po) {
        super.preUpdate(updateForm,po);
        if (!isStrEmpty(updateForm.getRefundNo())) {
            OrderRefund byId = getById(updateForm.getId());
            // 如果退款单号有改动
            if (!isEqual(updateForm.getRefundNo(), byId.getRefundNo())) {
                // 退款单号已存在不能修改
                assertByColumn(updateForm.getRefundNo(),OrderRefund::getRefundNo,false);
            }
        }

    }

    @Override
    public String generateOrderRefundNO(String categoryDictValue) {
        String orderRefundNO = null;
        for (IOrderRefundNoGeneratorService orderRefundNoGeneratorService : orderRefundNoGeneratorServices) {
            orderRefundNO = orderRefundNoGeneratorService.generateOrderRefundNo(categoryDictValue);
            if (orderRefundNO != null) {
                break;
            }
        }
        if (orderRefundNO == null) {
            throw new BusinessException("订单号生成失败");
        }
        return orderRefundNO;
    }
}
